package com.guanzi.server.controller;

import com.guanzi.server.entity.Store;
import com.guanzi.server.entity.dto.StoreSaveDTO;
import com.guanzi.server.query.StoreListQuery;
import com.guanzi.server.query.StoreOrderListQuery;
import com.guanzi.server.service.IStoreService;
import com.guanzi.server.util.Pager;
import com.guanzi.server.util.RespBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author guanzi
 * @since 2021-06-04
 */
@RestController
@RequestMapping("/store")
public class StoreController {

    @Autowired
    private IStoreService storeService;

    /**
     * 商家展示列表（包含分页）
     *
     * @param storeListQuery
     * @return
     */
    @PostMapping("/list")
    public RespBean searchOrList(StoreListQuery storeListQuery) {
        Pager<Store> pager = storeService.getListByName(storeListQuery);
        if (pager == null) {
            return RespBean.error("查询失败！输入的参数有误");
        }
        return RespBean.success("查询成功！", pager);
    }

    /**
     * 展示列表（点餐界面，暂不包含分页）
     * 对印的Query => StoreOrderListQuery
     * @param storeOrderListQuery
     * @return
     */
    @PostMapping("/orderList")
    public RespBean orderList(StoreOrderListQuery storeOrderListQuery) {
        List<Store> stores = storeService.getOrderList(storeOrderListQuery);
        if (stores == null) {
            return RespBean.error("查询失败！输入的参数有误");
        }
        return RespBean.success("查询成功！", stores);
    }

    /**
     * 添加或更新
     * 对应的Dto => StoreSaveDTO
     * @param store
     * @return
     */
//    @PostMapping("/save")
//    public RespBean save(Store store) {
//        storeService.saveStore(store);
//        return RespBean.success("保存成功！");
//    }

    /**
     * 商家信息和图片保存
     * @param storeSaveDTO
     * @return
     * @throws IOException
     */
    @PostMapping("/save")
    public RespBean save(StoreSaveDTO storeSaveDTO) throws IOException {
        storeSaveDTO.setImg( Base64Utils.encodeToString(storeSaveDTO.getPic().getBytes()) );
        System.out.println(storeSaveDTO);
        Boolean yOn = storeService.saveSTore(storeSaveDTO);
        if ( yOn ) {
            return RespBean.success("商家信息已保存！", storeSaveDTO.getImg());
        }
        return RespBean.error("商家名称已被使用！");
    }


    /**
     * 还没实现批量删除，这里只是单个的删除
     * @return
     */
    @GetMapping("/delete")
    public RespBean delete( @RequestParam("id")Integer id ) {
        storeService.delete(id);
        return RespBean.success("删除成功！");
    }

    /**
     * 批量删除 (还没测试是否能用)
     * @param ids
     * @return
     */
    @GetMapping("/deleteIds")
    public RespBean delete( @RequestParam("ids") String[] ids ) {
        storeService.delete(ids);
        return RespBean.success("批量删除成功！");
    }
}
